/**
 *
 */
package cn.hg.jfsa.manage.service;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;

import com.jfinal.kit.Kv;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.SqlPara;
import com.jfinal.plugin.ehcache.CacheKit;
import com.jfinal.plugin.ehcache.IDataLoader;

import cn.hg.jfsa.model.JfsaDict;

/**
 * @author Golly
 */
public class JfsaDictService {

	/**
	 * @param dict
	 */
	public void del (JfsaDict dict) {
		this.del(dict, true);
	}

	/**
	 * @param dict
	 * @param withChildren
	 */
	public void del (JfsaDict dict, boolean withChildren) {

		if (withChildren) {
			this.delWithChildren(dict);
		} else {
			dict.setStatus("del").update();
		}

	}

	public List<JfsaDict> getByParentKey (String parentKey, String status) {
		List<JfsaDict> list = CacheKit.get("jfsaDict", "dictList_" + parentKey + "_" + status, new IDataLoader() {

			@Override
			public Object load () {
				Kv para = Kv.by("parentKey", parentKey).set("status", status);
				SqlPara sqlPara = JfsaDict.DAO.getSqlPara("system.findDict", para);
				return JfsaDict.DAO.find(sqlPara);
			}

		});
		return list;
	}

	/**
	 * @return
	 */
	public List<JfsaDict> getTree () {
		List<JfsaDict> tree = CacheKit.get("jfsaDict", "tree");

		if (null == tree) {
			List<JfsaDict> list = JfsaDict.DAO.find("SELECT * FROM jfsa_dict WHERE status=?", "on");
			tree = this.buildTree(list, 0);
			tree.add(0, new JfsaDict().setId(0).setName("-- 顶层 --").setParentId(0).setStatus("on")
				.setCreatorId(1).setEditorId(1).setLayerNum(0));
			CacheKit.put("jfsaDict", "tree", tree);
		}

		return tree;
	}

	/**
	 * @param dict
	 */
	public void updateDictChildredIds (JfsaDict dict) {

		if (null == dict) {
			return;
		}

		String childrenIds = Db.queryFirst("SELECT GROUP_CONCAT(id) FROM jfsa_dict WHERE status<>'del' AND parent_id=?",
			dict.getId());
		dict.setChildrenIds(childrenIds).update();
	}

	/**
	 * @param list
	 * @param parentId
	 *
	 * @return
	 */
	private List<JfsaDict> buildTree (final List<JfsaDict> list, Integer parentId) {
		List<JfsaDict> tree = new ArrayList<>();

		for (JfsaDict bean : list) {

			if (parentId.equals(bean.getParentId())) {
				tree.add(bean);
			}

		}

		for (JfsaDict bean : tree) {
			bean.setChildren(this.buildTree(list, bean.getId()));
		}

		tree.sort(new Comparator<JfsaDict>() {

			@Override
			public int compare (JfsaDict o1, JfsaDict o2) {
				return o1.getSortNum().compareTo(o2.getSortNum());
			}

		});
		return tree;
	}

	/**
	 * @param dict
	 */
	private void delWithChildren (JfsaDict dict) {
		dict.setStatus("del").update();
		List<JfsaDict> childrenList = JfsaDict.DAO.find("SELECT * FROM jfsa_dict WHERE status<>'del' AND parent_id = ?",
			dict.getId());

		for (JfsaDict child : childrenList) {
			child.setStatus("del").update();
			this.delWithChildren(child);
		}

	}

}
